package external_sort_algorithms;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import utils.ArgumentAssertion;

import file_utils.FileIterator;
import file_utils.FileUtils;

public class ExternalMergeSort {

	public static void sort(String inputFilePath, String outputFilePath,
	        long bufferSizeInBytes) throws IOException {

		ArgumentAssertion.assertNotNull("inputFilePath", inputFilePath);
		ArgumentAssertion.assertNotNull("outputFilePath", inputFilePath);

		File inputFile = new File(inputFilePath);

		BufferedWriter outputWriter = new BufferedWriter(new FileWriter(
		        outputFilePath));

		File chunkFolder = FileUtils.divideIntoSortedChunks(inputFile,
		        bufferSizeInBytes);

		// if chunkFolder contains one file
		// if chunkFolder contains no file
		// if chunkFolder contains an empty file

		File[] files = chunkFolder.listFiles();

		List<Iterator<String>> fileIterators = new ArrayList<Iterator<String>>(
		        files.length);

		for (File file : files)
			fileIterators.add(new FileIterator(file));

		ScalableSortUtils.mergeAndWrite(fileIterators,
		        String.CASE_INSENSITIVE_ORDER, outputWriter);

		for (File file : files)
			file.delete();

		chunkFolder.delete();
	}
}
